

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title></title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=0">
    <link rel="stylesheet" href="../plugins/layui/css/layui.css?v=${.Config.basic.version}" media="all">
    <link rel="stylesheet" href="../plugins/layui/css/style.css?v=${.Config.basic.version}" media="all">
    <link rel="stylesheet" href="../plugins/layui/css/add.css?v=${.Config.basic.version}" media="all">
    <link rel="stylesheet" href="../layuiadmin/style/admin.css?v=${.Config.basic.version}" media="all">
    <link rel="stylesheet" href="../plugins/zTree/css/metroStyle/metroStyle.css?v=${.Config.basic.version}">
    <link rel="stylesheet" href="../plugins/toastr/toastr.min.css?v=${.Config.basic.version}">
    <style>
        .ztree li a {
            cursor: pointer;
            color: #333;
        }
        .layui-colla-title {
            position: relative;
            height: 42px;
            line-height: 42px;
            padding: 0 15px 0 35px;
            color: #333;
            background-color: transparent;
            cursor: pointer;
            font-size: 14px;
            overflow: hidden;
        }
    </style>
</head>
<body>

<div class="layui-fluid">
    <div class="layui-row layui-col-space15">
        <div class="layui-col-xs3">
            <div class="layui-card">
                <div class="layui-card-header">
                    <span>角色</span>

                </div>
                <div class="layui-card-body">
                    <div class="tree-div scroll">
                        <ul id="treeDemo" class="ztree"></ul>
                    </div>
                </div>
            </div>
        </div>
        <div class="layui-col-xs9">
            <div class="layui-card">
                <div class="layui-card-header "><span class="title"></span><a href="javascript:location.reload();" title="刷新">
                        <i class="layui-icon layui-icon-refresh-3"></i>
                    </a></div>
                <div class="layui-card-body">
                    <div class="tree-div scroll">
                        <form class="layui-form " lay-filter="func-form" id="func-form" style="padding: 20px 30px 0 0;">
                            <div class="layui-form-item layui-hide" >
                                <label class="layui-form-label">ID</label>
                                <div class="layui-input-inline">
                                    <input type="text" name="id" lay-verify="required" placeholder="请输入ID" autocomplete="off" class="layui-input">
                                </div>
                            </div>
                            <!--<div class="layui-form-item">
                                <label class="layui-form-label">名称</label>
                                <div class="layui-input-inline">
                                    <input type="text" name="name" lay-verify="required" placeholder="请输入名称" autocomplete="off" class="layui-input">
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <label class="layui-form-label">名称(英文)</label>
                                <div class="layui-input-inline">
                                    <input type="text" name="name_en" lay-verify="" placeholder="请输入名称(英文)" autocomplete="off" class="layui-input">
                                </div>
                            </div>-->
                            <div id="func-content" class="layui-collapse" lay-filter="func-content">

                            </div>
                            <div class="layui-form-item">
                            </div>
                            <div class="layui-form-item">
                                <div class="layui-input-block">
                                    <button type="submit" class="layui-btn layui-btn-normal layui-hide action-edit hide" lay-submit="" lay-filter="btn_save" id="btn_save">保存</button>
                                    <!-- <button type="submit" class="layui-btn layui-btn-normal layui-hide action-edit hide" lay-submit="" lay-filter="btn_add" id="btn_add">新增</button> -->
                                    <button type="reset" id="btn_cancel" class="layui-btn layui-btn-primary">重置</button>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>

            </div>
        </div>
    </div>
</div>



<script src="../plugins/layui/layui.js"></script>
<script src="../plugins/jquery/jquery-3.6.0.js?v=${.Config.basic.version}"></script>
<script src="../plugins/zTree/js/jquery.ztree.core.min.js?v=${.Config.basic.version}"></script>
<script src="../plugins/zTree/js/jquery.ztree.excheck.js?v=${.Config.basic.version}"></script>
<script src="../plugins/zTree/js/jquery.ztree.exedit.js?v=${.Config.basic.version}"></script>
<script src="../plugins/toastr/toastr.min.js"></script>
<script>
    var zTree=null;
    var table=null;
    var form=null;
    var element=null;
    var iconPicker =null;
    var Table=null;
    var actions=null;
    var token = window.localStorage.getItem("token");
    var user_info=JSON.parse(window.localStorage.getItem("user_info"));
    var is_admin = user_info.is_admin;
    var func_url="${.func_url}";
    var actions=[];
    token = 'Bearer ' + token;
    layui.config({
        base: '../layuiadmin/' //静态资源所在路径
    }).extend({
        index: 'lib/index' //主入口模块
    }).use(['index', 'table','form','element'], function(){
        $ = layui.$;
        form = layui.form;
        element = layui.element;
        toastr.options = {
            "closeButton": false, //是否显示关闭按钮
            "debug": false, //是否使用debug模式
            "positionClass": "toast-top-center",//弹出窗的位置
            "showDuration": "300",//显示的动画时间
            "hideDuration": "1000",//消失的动画时间
            "timeOut": "2000", //展现时间
            "extendedTimeOut": "1000",//加长展示时间
            "showEasing": "swing",//显示时的动画缓冲方式
            "hideEasing": "linear",//消失时的动画缓冲方式
            "showMethod": "fadeIn",//显示时的动画方式
            "hideMethod": "fadeOut" //消失时的动画方式
        };

        $.ajax({
            type: 'GET',
            url: '../Api/User/Actions',
            data: {func_url:func_url},
            beforeSend: function(request) {
                request.setRequestHeader("Authorization", 'Bearer '+window.localStorage.getItem("token"));
            },
            dataType: "json",
            success: function (data) {
                console.info(data)
                actions=data.data;
                for(var i=0;i<actions.length;i++){
                    $('.action-'+actions[i].action_id).removeClass("layui-hide");
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                layer.msg('加载操作信息失败');
            }
        });
        var tree_setting = {
            view: {
                dblClickExpand: false,
                fontCss: getFont,
                nameIsHTML: true,
                //addHoverDom: addHoverDom,
                removeHoverDom: removeHoverDom,
            },
            callback: {
                onClick: treeOnClick
            },
            edit: {
                enable: false,
            },
            data: {
                key:{
                    name:"name"
                },
                simpleData: {
                    enable: true,
                    idKey: 'id',
                    pIdKey: '',
                    rootPId: null
                }
            }
        };
        function getFont(treeId, node) {
            return node.font ? node.font : {};
        }

        function addHoverDom(treeId, treeNode) {

            var sObj = $("#" + treeNode.tId + "_span");
            if (treeNode.editNameFlag || $("#removeBtn_"+treeNode.tId).length>0) return;

            var removeStr = "<span class='button remove' nodeid='"+treeNode.tId+"' id='removeBtn_" + treeNode.tId
                + "' title='remove node' onfocus='this.blur();'></span>";
            sObj.after(removeStr);

            btn = $("#removeBtn_"+treeNode.tId);
            if (btn) btn.bind("click", function(event){
                var tid=$(this).attr("nodeid");
                var node = zTree.getNodeByTId(tid);
                console.info(node);
                layer.confirm('确认删除'+node.role_name+"?", function(index){
                    layer.close(index);
                    $.ajax({
                        type: 'DELETE',
                        url: '../Api/Permission',
                        data: {id:node.role_id},
                        beforeSend: function(request) {
                            request.setRequestHeader("Authorization", 'Bearer ' + window.localStorage.getItem("token"));
                        },
                        dataType: "json",
                        success: function (data) {
                            //console.info(data)
                            if(data.code>=0){
                                layer.msg('删除成功');
                                window.location.reload();
                            }else{
                                layer.alert('删除失败:'+data.msg);
                            }
                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                            layer.alert('删除失败');
                        }
                    });
                });

                return false;
            });
        };
        function removeHoverDom(treeId, treeNode) {
            $("#removeBtn_"+treeNode.tId).unbind().remove();
        };
        function treeOnClick(event, treeId, treeNode) {
            //编辑模式
            $("input[name='id']").attr("disabled","");
            $('#btn_add').addClass("hide");
            $('#btn_save').removeClass("hide");
            $.ajax({
                type: 'GET',
                url: '../Api/Permission',
                data: {role_id:treeNode.id},
                beforeSend: function(request) {
                    request.setRequestHeader("Authorization", 'Bearer '+window.localStorage.getItem("token"));
                },
                dataType: "json",
                success: function (data) {
                    console.info(data);
                    $("#btn_cancel").click();
                    var list=data.data;
                    if(list.length>0){
                        var obj={};
                        obj['id']=list[0].role_id;
                        obj['name']=list[0].role_name;
                        obj['name_en']=list[0].role_name_en;
                        for(var i=0;i<list.length;i++){
                            var name = list[i].func_id+"["+list[i].action_id+"]";
                            obj[name]=true;
                        }

                        form.val("func-form", obj);
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    layer.msg('加载信息失败');
                }

            });
        }

        //监听折叠
        element.on('collapse(func-content)', function(data){
            //layer.msg('展开状态：'+ data.show);
        });
        //监听提交
        form.on('submit(btn_save)', function(data){
            var field = data.field; //获取提交的字段
            //console.info(field);
            //return ;

            var permission=[];
            for(var prop in field){
                var start=prop.indexOf('[');
                var end = prop.indexOf(']');
                if (start>0 && end>0){

                    var func_id=prop.substring(0,start);
                    var action_id=prop.substring(start+1,end);
                    permission.push({role_id:field['id'],func_id:func_id,action_id:action_id});
                    delete prop;
                }
            }
            field['permission']=JSON.stringify(permission);
            console.info(field);
            //return  false;

            $.ajax({
                type: 'PUT',
                url: '../Api/Permission',
                contentType: 'application/json',
                data: field,
                beforeSend: function(request) {
                    request.setRequestHeader("Authorization", 'Bearer ' + window.localStorage.getItem("token"));
                },
                dataType: "json",
                success: function (data) {
                    //console.info(data)
                    if(data.code>=0){
                        toastr.success("保存成功");
                    }else{
                        layer.alert('保存失败:'+data.msg);
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    layer.alert('保存失败');
                }
            });
            return false;
        });
        form.on('submit(btn_add)', function(data){
            var field = data.field; //获取提交的字段
            var permission=[];
            for(var prop in field){
                var start=prop.indexOf('[');
                var end = prop.indexOf(']');
                if (start>0 && end>0){

                    var func_id=prop.substring(0,start);
                    var action_id=prop.substring(start+1,end);
                    permission.push({role_id:field['id'],func_id:func_id,action_id:action_id});
                    delete prop;
                }
            }
            field['permission']=JSON.stringify(permission);
            $.ajax({
                type: 'POST',
                url: '../Api/Permission',
                data: field,
                beforeSend: function(request) {
                    request.setRequestHeader("Authorization", 'Bearer ' + window.localStorage.getItem("token"));
                },
                dataType: "json",
                success: function (data) {
                    //console.info(data)
                    if(data.code>=0){
                        toastr.success("保存成功");
                        window.location.reload();
                    }else{
                        layer.alert('保存失败:'+data.msg);
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    layer.alert('保存失败');
                }
            });
            return false;
        });

        $.ajax({
            type: 'GET',
            url: '../Api/Func',
            data: {},
            beforeSend: function(request) {
                request.setRequestHeader("Authorization", 'Bearer '+window.localStorage.getItem("token"));
            },
            dataType: "json",
            success: function (data) {

                var funcs=data.data;
                //请求action
                $.ajax({
                    type: 'GET',
                    url: '../Api/Action',
                    data: {},
                    beforeSend: function(request) {
                        request.setRequestHeader("Authorization", 'Bearer '+window.localStorage.getItem("token"));
                    },
                    dataType: "json",
                    success: function (data) {
                        actions=data.data;

                        var html="";

                        console.info(funcs);
                        for(var i=0;i<funcs.length;i++){
                            if(!is_admin)
                            {
                                if(funcs[i].admin_only>0){
                                    continue;
                                }
                            }
                            console.info(funcs[i].name);
                            if(funcs[i].level==0){

                                var action_html="";
                                for(var a=0;a<actions.length;a++){
                                    if(funcs[i].action_ids){
                                        var func_action_arr = funcs[i].action_ids.split(",");
                                        if(func_action_arr.indexOf(actions[a].id)>=0){
                                            action_html+="<input type=\"checkbox\" name=\""+funcs[i].id+"["+actions[a].id+"]\" title=\""+actions[a].name+"\" >";
                                        }
                                    }
                                }

                                html+="  <div class=\"layui-colla-item\">\n" +
                                    "    <h2 class=\"layui-colla-title\">"+funcs[i].name+"</h2>\n" +
                                    "    <div class=\"layui-colla-content layui-show\">"+action_html+"</div>\n" +
                                    "  </div>";
                                for(var j = 0;j<funcs.length;j++){
                                    
                                    if(funcs[j].pid==funcs[i].id){
                                        if(!is_admin)
                                        {
                                            if(funcs[j].admin_only>0){
                                                continue;
                                            }
                                        }
                                        console.info(funcs[j].name);

                                        action_html="";

                                        for(var b=0;b<actions.length;b++){
                                            //action_html+="<input type=\"checkbox\" name=\""+funcs[j].id+"["+actions[b].id+"]\" title=\""+actions[b].name+"\" >";
                                            if(funcs[j].action_ids){
                                                var func_action_arr = funcs[j].action_ids.split(",");
                                                if(func_action_arr.indexOf(actions[b].id)>=0){
                                                    action_html+="<input type=\"checkbox\" name=\""+funcs[j].id+"["+actions[b].id+"]\" title=\""+actions[b].name+"\" >";
                                                }
                                            }
                                        }
                                        html+="  <div class=\"layui-colla-item\">\n" +
                                            "    <h2 class=\"layui-colla-title\">&nbsp;&nbsp;|--"+funcs[j].name+"</h2>\n" +
                                            "    <div class=\"layui-colla-content layui-show\">"+action_html+"</div>\n" +
                                            "  </div>";
                                        for(var k=0;k<funcs.length;k++){
                                            if(funcs[k].pid==funcs[j].id){
                                                action_html="";
                                                console.info(funcs[k].name);

                                                for(var c=0;c<actions.length;c++){
                                                    //action_html+="<input type=\"checkbox\" name=\""+funcs[j].id+"["+actions[b].id+"]\" title=\""+actions[b].name+"\" >";
                                                    if(funcs[k].action_ids){
                                                        var func_action_arr = funcs[k].action_ids.split(",");
                                                        if(func_action_arr.indexOf(actions[c].id)>=0){
                                                            action_html+="<input type=\"checkbox\" name=\""+funcs[k].id+"["+actions[c].id+"]\" title=\""+actions[c].name+"\" >";
                                                        }
                                                    }
                                                }
                                                html+="  <div class=\"layui-colla-item\">\n" +
                                                    "    <h2 class=\"layui-colla-title\">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;|--"+funcs[k].name+"</h2>\n" +
                                                    "    <div class=\"layui-colla-content layui-show\">"+action_html+"</div>\n" +
                                                    "  </div>";
                                            }
                                        }
                                    }
                                }
                            }

                        }
                        $('#func-content').html(html);
                        element.render('collapse');
                        form.render('checkbox');
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        layer.msg('加载信息失败');
                    }

                });


            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                layer.msg('加载信息失败');
            }

        });

        $.ajax({
            type: 'GET',
            url: '../Api/Role/List',
            data: {},
            beforeSend: function(request) {
                request.setRequestHeader("Authorization", 'Bearer '+window.localStorage.getItem("token"));
            },
            dataType: "json",
            success: function (res) {
                if(res.code>=0){
                    var data = res.data;
                    for(var i=0;i<data.length;i++){
                        data[i]["icon"]="../plugins/zTree/css/metroStyle/img/role.png";
                    }
                    zTree = $.fn.zTree.init($("#treeDemo"), tree_setting, data);
                    zTree.expandAll(true);
                }
                
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                layer.msg('加载信息失败');
            }

        });

        resizeElement();
    });

    function add(){
        $("input[name='id']").removeAttr("disabled");
        $('#btn_add').removeClass("hide");
        $('#btn_save').addClass("hide");

        $("#btn_cancel").click();
        $('.title').html("新增");
        layer.alert("已经进入新增模式，点击[新增]按钮保存");
    }

    $(window).resize(function () {
        //console.info('resize')
        resizeElement();
    });
    function resizeElement() {
        $('.tree-div').height($(window).height()-110);
    }

</script>
<script src="../js/check_screen.js?v=${.Config.basic.version}"></script>

</body>
</html>

